//
//  DeviceDetailInfo.m
//  efairy
//
//  Created by 李锋 on 2019/1/16.
//  Copyright © 2019年 East. All rights reserved.
//

#import "DeviceDetailInfo.h"
#import "YYModel.h"
#import "MJRefresh.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "DeviceListModel.h"
#import "EFAModel.h"
#import "DeviceDetailCell.h"
#import "EFAMaintenanceVC.h"
#import "EFAMsgControlCVC.h"
#import "EFADevInfoImgTCell.h"
#import "KSPhotoBrowser.h"
#import <UIScrollView+EmptyDataSet.h>
#import "DeviceCompleteImgCell.h"
#import "DeviceRealTimeDataCell.h"
#import "PassagewayInfoCell.h"
#import "DeviceUserCell.h"

@interface DeviceDetailInfo ()<UITableViewDelegate,UITableViewDataSource,EFADevInfoImgTCellDelegate,DZNEmptyDataSetDelegate, DZNEmptyDataSetSource,btnClickedDelegate>
@property (strong, nonatomic) UIBarButtonItem *maintenanceBarBtnItem;
@property (nonatomic, strong) MJRefreshComponent *refreshViewComponent;
@property (strong,  nonatomic) UITableView *tableView;
@property (strong,  nonatomic) UITableView *tableViewPhone;
@property (strong,  nonatomic) UILabel *cancel;
@property (strong,  nonatomic) UIView *phoneView;
@property (strong,  nonatomic) UIImageView *imageView;
@property(nonatomic,strong) DeviceListModel *deviceListModel;
@end
//static NSString *const detailCellIdentifier = @"DeviceDetailCell";//设备基本信息identifier（标识符）；
//static NSString *const  imgCellIdentifier = @"DeviceRealTimeDataCell";//设备竣工图
//static NSString *const  rtCellIdentifier = @"DeviceRealTimeDataCell";//设备实时信息
//static NSString *const  PassageawayCellIdentifier = @"PassagewayInfoCell";//设备实时信息



@implementation DeviceDetailInfo


- (void)dealloc
{
    //当对象被回收时关闭通知
     [[NSNotificationCenter defaultCenter] removeObserver:self name:EFAGlobalNotiPassageway object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self setupView];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"设备信息";
    self.navigationItem.rightBarButtonItems = @[self.maintenanceBarBtnItem];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}


-(void)setupView{
    float  navigationbar = self.navigationController.navigationBar.frame.size.height;
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, statusBarHeight+navigationbar, SCREEN_WIDTH, SCREEN_HEIGHT-statusBarHeight-navigationbar)];
    self.tableView.backgroundColor = BG;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 252.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    
    
//     [self.tableView registerClass:[DeviceDetailCell class] forCellReuseIdentifier:detailCellIdentifier];
//    UINib *imgNib = [UINib nibWithNibName:@"EFADevInfoImgTCell" bundle:nil];
//    [self.tableView registerNib:imgNib forCellReuseIdentifier:@"EFADevInfoImgTCell"];
    //多余分割线不显示
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    _imageView = [[UIImageView alloc]init];
    _imageView.image = [UIImage imageNamed:@"icon_call_phone"];
    _imageView.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tapShowPhone=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickShowPhone:)];
    [_imageView addGestureRecognizer:tapShowPhone];
    
    
    [self.view sd_addSubviews:@[ self.tableView,_imageView]];
    _imageView.sd_layout.widthIs(63)
    .heightIs(63)
    .bottomSpaceToView(self.view, 20)
    .rightSpaceToView(self.view, 20);
    
    
     UIWindow *wd = [[UIApplication sharedApplication].windows lastObject];
    _phoneView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _phoneView.backgroundColor =[UIColor colorWithWhite:0.f alpha:0.6];//设置黑白背景色
//    _phoneView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];//设置任意颜色背景色
    _phoneView.hidden = YES;
    [wd addSubview:_phoneView];
    
    self.tableViewPhone = [UITableView new];
    self.tableViewPhone.backgroundColor =  [UIColor whiteColor];
    self.tableViewPhone.delegate = self;
    self.tableViewPhone.dataSource = self;
    self.tableViewPhone.layer.cornerRadius = 6;//设置圆角
    
    _cancel = [[UILabel alloc]init];
    _cancel.layer.backgroundColor =[UIColor whiteColor].CGColor;
    _cancel.layer.cornerRadius = 6;
    _cancel.textColor = ColorFromRGB(0x333333);
    _cancel.font = [UIFont systemFontOfSize:18.f];
    _cancel.textAlignment = NSTextAlignmentCenter;
    _cancel.text=@"取消";
    _cancel.userInteractionEnabled = YES;
//    _cancel.layoutMargins = UIEdgeInsetsMake(12, 12, 12, 12);//设置margin
    UITapGestureRecognizer *tapClose=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickShowPhone:)];
    [_cancel addGestureRecognizer:tapClose];
    
    [_phoneView sd_addSubviews:@[self.tableViewPhone,_cancel]];
    _cancel.sd_layout.heightIs(50)
    .leftSpaceToView(_phoneView, 12)
    .rightSpaceToView(_phoneView, 12)
    .bottomSpaceToView(_phoneView, 20);
    
    self.tableViewPhone.sd_layout
    .heightIs(240)
    .leftSpaceToView(_phoneView, 12)
    .rightSpaceToView(_phoneView, 12)
    .bottomSpaceToView(_cancel, 8);
    
    
  
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    __weak typeof(self) weakSelf = self;
    //..下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.refreshViewComponent = weakSelf.tableView.mj_header;
        [weakSelf requestDeviceInfo];
    }];
    
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
}


-(void)onClickShowPhone:(id)tap{
    NSLog(@"点击了电话图片");
    if(_phoneView.isHidden){
        [self.tableViewPhone reloadData];
        _phoneView.hidden = NO;
    }else{
        _phoneView.hidden = YES;
    }
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"当前没有信息" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    //    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
    return nil;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource

//执行几次tableview（一般看添加几个cell）
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if([tableView isEqual:self.tableView]){
         return 4;
    }else if([tableView isEqual:self.tableViewPhone]){
        return 1;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if([tableView isEqual:self.tableView]){
        if(section == 0){
            return _deviceListModel.basic_info ? 1: 0;//基本信息cell
        }else if(section == 1){
            return 1;//_deviceListModel.efairydevice_imgurl_list.count ? 1 : 0;//竣工图cell
        }else if(section == 2){
            return 1;
        }else if(section == 3){
            if(_deviceListModel.rt_info){
                if(_deviceListModel.rt_info.c_data_list){
                    return 1;
                }
            }
        }
    }else if([tableView isEqual:self.tableViewPhone]){
        return _deviceListModel.user_list?_deviceListModel.user_list.count:0;//用户联系电话
    }
   
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if([tableView isEqual:self.tableView]){
        if(indexPath.section == 0){
            //不是cib布局用这个
            DeviceDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"DeviceDetailCell" description]];
            if(!cell){
                cell = [[DeviceDetailCell alloc]init];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setModelData:_deviceListModel.basic_info];
            // 此步设置用于实现cell的frame缓存，可以让tableview滑动更加流畅
            [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
            return cell;
        }else if (indexPath.section == 1){
            DeviceCompleteImgCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"DeviceCompleteImgCell" description]];
            if(!cell){
                cell = [[DeviceCompleteImgCell alloc]init];
                
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell configViewWithImgArray:_deviceListModel.efairydevice_imgurl_list];
            cell.delegate = self;
            return cell;
        }else if(indexPath.section == 2){
            DeviceRealTimeDataCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"DeviceRealTimeDataCell" description]];
            if(!cell){
                cell = [[DeviceRealTimeDataCell alloc]init];
            }
            
            if(_deviceListModel.basic_info){
                cell.deviceId = _deviceListModel.basic_info.efairydevice_id;
                cell.deviceName = _deviceListModel.basic_info.efairydevice_name;
            }
            //禁止cell点击选中
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setModeData:_deviceListModel.rt_info];
            return cell;
        }else if(indexPath.section == 3){
            PassagewayInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"PassagewayInfoCell" description]];
            if(!cell){
                cell = [[PassagewayInfoCell alloc]init];
            }

            cell.btnDelegate = self;
            //禁止cell点击选中
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            //        [cell setModeDatas:_deviceListModel.rt_info.c_data_list[indexPath.row]];
            [cell setModeAllDatas:_deviceListModel.rt_info.c_data_list];
            return cell;
        }
        
    }else if([tableView isEqual:self.tableViewPhone]){
        DeviceUserCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"DeviceUserCell" description]];
        if(!cell){
            cell = [[DeviceUserCell alloc]init];
        }
        [cell setModeDatas:_deviceListModel.user_list[indexPath.row]];
        return cell;
    }
   
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:tableView];
    //    return [tableView cellHeightForIndexPath: indexPath];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor whiteColor];
}

//接受点击cell item项
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if([tableView isEqual:self.tableViewPhone]){
        [self callSomeOneWithPhoneNum:_deviceListModel.user_list[indexPath.row].efairyuser_phonenumber];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//根基手机号自动跳到打电话页面
- (void)callSomeOneWithPhoneNum:(NSString *)num {
    NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", num];
    NSLog(@"电话%@",callPhone);
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }
}


#pragma mark - network request
- (void)requestDeviceInfo{
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        //        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
         [self.tableView.mj_header endRefreshing];
        return;
    }
    
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairydevice_id" : @(self.deviceId),
                           };
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiDevice] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求设备信息返回：%@", responseObject);
        //停止刷新头部
        [self.tableView.mj_header endRefreshing];
        _deviceListModel = [DeviceListModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        //        [self.deviceInfo unzipStreamList];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求设备信息失败：%@", error);
        //停止刷新头部
        [self.tableView.mj_header endRefreshing];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}


//刷新数据
- (void)refreshWholeView {
    [self.tableView reloadData];
}


#pragma mark - getters and setters
- (UIBarButtonItem *)maintenanceBarBtnItem {
    if (!_maintenanceBarBtnItem) {
        _maintenanceBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"device_maintenance"] style:UIBarButtonItemStylePlain target:self action:@selector(maintenanceBarBtnItemTapped:)];
    }
    return _maintenanceBarBtnItem;
}


- (void)maintenanceBarBtnItemTapped:(UIBarButtonItem *)item {
    EFAMaintenanceVC *vc = [[EFAMaintenanceVC alloc] init];
    vc.device_id = self.deviceId;
    [self showViewController:vc sender:nil];
}

#pragma mark - private methods
- (void)showPhotoBrowser:(NSArray<KSPhotoItem *> *)photoItems selectedIndex:(NSUInteger)index {
    KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:photoItems selectedIndex:index];
    browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleNone;
    browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlack;
    browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
    browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
    browser.bounces = NO;
    [browser showFromViewController:self];
}


#pragma mark - EFADevInfoImgTCellDelegate
- (void)devInfoImgTCell:(EFADevInfoImgTCell *)cell imgViewTapped:(NSArray<UIImageView *> *)imgViewArray indexPath:(NSIndexPath *)cIndexPath {
    if (cIndexPath.row >= _deviceListModel.efairydevice_imgurl_list.count) {
        return;
    }
    
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:_deviceListModel.efairydevice_imgurl_list.count];
    [_deviceListModel.efairydevice_imgurl_list enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImageView *tempImgView = nil;
        if (idx < imgViewArray.count) {
            tempImgView = imgViewArray[idx];
        }
        KSPhotoItem *photoItem = [KSPhotoItem itemWithSourceView:tempImgView imageUrl:[NSURL URLWithString:obj]];
        [mArray addObject:photoItem];
    }];
    [self showPhotoBrowser:mArray selectedIndex:cIndexPath.row];
}

//实现passageawyCell 代理方法，用于执行通道修改功能
-(void)cellSubmitClicked:(NSMutableArray<UITextField *>*)uiTextFileArray{
    if(uiTextFileArray != nil && uiTextFileArray.count >0){
        NSMutableArray *nameArray = [[NSMutableArray alloc]init];
        for(int i =0; i<uiTextFileArray.count;i++){
            NSDictionary *cname = @{@"c_name":uiTextFileArray[i].text};
                NSDictionary *pinfo = @{@"efairydevicechannelsetting_cid":@(_deviceListModel.rt_info.c_data_list[i].cid),
                                        @"efairydevicechannelsetting_setting":cname};
            [nameArray addObject:pinfo];
        }
        [self updatePassagewayName:nameArray andTextFileArray:uiTextFileArray];
    }
}



//通道名称修改
-(void)updatePassagewayName:(NSMutableArray *)nMArray andTextFileArray:(NSMutableArray<UITextField *>*)array{
    // 发布帖子
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairydevice_id" : @(_deviceListModel.basic_info.efairydevice_id),
                           @"channel_setting_list" : nMArray};
    NSLog(@"发布公告的请求参数：%@", pars);
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiPassagewayUpdate] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hideAnimated:NO];
       [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"通道名修改成功"];
        [[NSNotificationCenter defaultCenter] postNotificationName:EFAGlobalNotiPassageway object:@"success"];
        for(int i=0;i<array.count;i++){
            _deviceListModel.rt_info.c_data_list[i].c_name=array[i].text;
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [[NSNotificationCenter defaultCenter] postNotificationName:EFAGlobalNotiPassageway object:@"fail"];
        for(int i=0;i<array.count;i++){
            array[i].text = _deviceListModel.rt_info.c_data_list[i].c_name;
        }
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

//- (void)backToParent {
//    if (self.successHandle) {
//        self.successHandle();
//        self.successHandle = nil;
//    }
//    [self.navigationController popViewControllerAnimated:YES];
//}
@end
